require(['config'], function() {
    require(['jquery', 'template', 'loadHeader', 'loadFooter', 'jquery.zoom', 'jquery.cookie'],($, template)=>{
        $.ajax({
            url: 'http://www.xiongmaoyouxuan.com/api/detail?id=87062100&normal=1&sa=',
            success(resData) {
              console.log('成功：', resData)
              // 拿到的数据
              // 放大镜内容
              const photos = resData.data.detail.photo
              console.log(photos);
              //详情内容
              const details = resData.data.detail

              // 渲染模板
              const fdj = template('photo-template', {photos})
              $('.img-box').html(fdj)
              
              const fl = template('fenlei-template', {photos})
              $('.ysfl').html(fl)

              const sc = template('sc-template', {details})
              $('.shoucang ').html(sc)

              const title = template('title-template', {details})
              $('.shopName').html(title)

              const price = template('price-template', {details})
              $('.price').html(price)


              // 添加放大镜效果
              $('.small-image').elevateZoom({
                gallery: 'gallery',
                galleryActiveClass: 'active'
              })
            }
        })
       
        /* 加、减数量 */
      $('.add').on('click', '.amount, .minus, .plus', e => {
        let amount =  Number($('.amount').val()) 

        // 判断点击的按钮
        if ($(e.target).is('.plus')) { // 加
          // console.log(1);
          amount++ 
          
        }else if ($(e.target).is('.minus')) { // 减
          if (amount <= 1) {
            // $('.minus').attr("cursor", "not-allowed")
            return
          }
          amount --
        }
        $('.amount').val(amount)
        
      })

      /* 添加购物车：为按钮绑定点击事件--利用事件委派 */
      $('.gm').on('click', '.jrgwc', e => {
        // 获取当前按钮所在的 li 节点
        const id = $('.id').val()
        const img = $('.small-image').attr('src')
        const title = $('.title').text().slice(31)
        const price = $('.tbjPrice').text()
        const amount = $('.amount').val()
        
        const carts = {
          id,
          img,
          title,
          price,
          amount
        }
        
        // 保存cookie
        $.cookie.json = true
        const cart = $.cookie('cart') || []
        const index = cart.findIndex(prod => prod.id === carts.id)
        if(index !== -1){
          carts[index].amount =Number(cart[index].amount) + Number(carts.amount)
        }else{
          cart.push(carts)
        }
        $.cookie('cart', cart, {expires:180, path:'/'} )
        location.href = '/html/cart.html'
      })
    })
})
